﻿using System;
using System.Collections;
using System.IO;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using UDS.Components;

namespace UDS.SubModule.UnitiveDocument.Document
{
    /// <summary>
    /// DeliverDocument 的摘要说明。
    /// </summary>
    public partial class DeliverDocumentPage : Page
    {
        protected static string Username;
        public string ClassID;
        public ArrayList listattfile = new ArrayList();

        private void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Session["listattfile"] = listattfile;
            }

            ClassID = (Request.QueryString["ClassID"] != null) ? Request.QueryString["ClassID"] : "";

            Username = SiteContext.Current.UserName;
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            AttUpload();
            listUpDoc.Items.Clear();
            int count = 0;
            var listattfile = (ArrayList) Session["listattfile"];
            foreach (DocAttachFile att in listattfile)
            {
                count++;
                listUpDoc.Items.Add(new ListItem(att.FileName, count.ToString()));
            }
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            var listattfile = (ArrayList) Session["listattfile"];
            for (int i = listUpDoc.Items.Count - 1; i >= 0; i--)
            {
                if (listUpDoc.Items[i].Selected)
                {
                    listUpDoc.Items.RemoveAt(i);
                    listattfile.RemoveAt(i);
                }
            }

            Session["listattfile"] = listattfile;
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            string DocID = "";
            DocBody docbody = ProcessFormPost();
            var doc = new DocumentClass();
            // 添加文档,并返回ID
            DocID = doc.AddDocBody(docbody);
            var listattfile = (ArrayList) Session["listattfile"];
            foreach (DocAttachFile att in listattfile)
            {
                try
                {
                    string userDirVPath = DocAttachFile.AttachVDir + Username + "\\";
                    string userDirPath = MapPath(userDirVPath);
                    var userDir = new DirectoryInfo(userDirPath);
                    if (!userDir.Exists)
                    {
                        userDir.Create();
                    }

                    var TempNameInt = new Random();
                    string NewDocDirName = TempNameInt.Next(100000000).ToString();

                    string newDocDirPath = Path.Combine(userDir.FullName, NewDocDirName);
                    Directory.CreateDirectory(newDocDirPath);

                    // Move the temporary file
                    File.Move(MapPath(att.FileVisualPath), Path.Combine(newDocDirPath, att.FileName));

                    // Remove the tmp directory
                    Directory.Delete(Path.GetDirectoryName(MapPath(att.FileVisualPath)), true);

                    att.FileVisualPath = userDirVPath + newDocDirPath + "\\" + att.FileName;
                    att.FileAddedDate = DateTime.Now.ToString();

                    // 附件数据库处理
                    doc.AddAttach(att, Int32.Parse(DocID));
                }
                catch (Exception ioex)
                {
                    Logger.Log(ioex.ToString());
                    Server.Transfer("../../Error.aspx");
                }
            }
            Response.Write("<script language=javascript>alert('文档提交成功!');self.location='../Switch.aspx?Action=1&ClassID=" + ClassID + "';</script>");
        }

        private void btnReturn_Click(object sender, EventArgs e)
        {
            Response.Redirect("../Switch.aspx?Action=1&ClassID=" + ClassID);
        }

        #region 处理表单post数据

        /// <summary>
        /// 处理表单post数据
        /// </summary>
        private DocBody ProcessFormPost()
        {
            //　验证
            if (Request.IsAuthenticated)
            {
                bool canApprove = AssignRights.IsAccessAllowed(Username, Int32.Parse(ClassID), PermissionType.ApproveDocument);

                // 处理表单传递参数
                var docbody = new DocBody();
                docbody.DocTitle = txtTitle.Value;
                docbody.DocContent = txtContent.Value;
                docbody.DocAddedBy = Username;
                docbody.DocClassID = Int32.Parse(ClassID);
                docbody.DocAddedDate = DateTime.Now.ToString();
                docbody.DocApprover = canApprove ? Username : "";
                docbody.DocApproveDate = canApprove ? DateTime.Now.ToString() : "";
                docbody.DocApproved = (docbody.DocApprover == "") ? 0 : 1;
                docbody.DocAttribute = 0;
                docbody.DocType = 0;
                return docbody;
            }
            return null;
        }

        #endregion

        #region 处理附件上传操作，传回附件数组

        /// <summary>
        /// 处理上传操作,附件以链接形式存放
        /// </summary>
        private ArrayList AttUpload()
        {
            var FrmCompose = (HtmlForm) Page.FindControl("DeliverDocument");
            var TempNameInt = new Random();
            string NewDocDirName = TempNameInt.Next(100000000).ToString();
            var listattfile = (ArrayList) Session["listattfile"];

            // 存放附件至提交人目录中，随机生成目录名

            string FileName = "";
            try
            {
                var tmpDir = new DirectoryInfo(DocAttachFile.TempAttachDir);
                if (tmpDir.Exists)
                {
                    string docTempVDir = DocAttachFile.TempAttachVDir + Username + "-" + NewDocDirName;
                    var docTempDir = new DirectoryInfo(MapPath(docTempVDir));
                    if (!docTempDir.Exists)
                    {
                        docTempDir.Create();
                    }

                    for (int i = 0; i < FrmCompose.Controls.Count; i++)
                    {
                        if (FrmCompose.Controls[i].GetType().ToString() == "System.Web.UI.HtmlControls.HtmlInputFile")
                        {
                            var hif = ((HtmlInputFile) (FrmCompose.Controls[i]));
                            if (hif.PostedFile.FileName.Trim() != "")
                            {
                                FileName = Path.GetFileName(hif.PostedFile.FileName);
                                var att = new DocAttachFile();
                                // 初始化
                                att.FileAttribute = 0;
                                att.FileSize = hif.PostedFile.ContentLength;
                                att.FileName = FileName;
                                att.FileAuthor = Username;
                                att.FileCatlog = "文档";
                                att.FileVisualPath = docTempVDir + "\\" + NewDocDirName;

                                hif.PostedFile.SaveAs(MapPath(att.FileVisualPath));
                                listattfile.Add(att);
                            }
                        }
                    }
                }
                else
                {
                    // Create the tmp directory.
                    tmpDir.Create();

                    AttUpload();
                }
            }
            catch (Exception ioex)
            {
                Logger.Log(ioex.ToString());
                Server.Transfer("../../Error.aspx");
            }

            Session["listattfile"] = listattfile;
            return listattfile;
        }

        #endregion

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN：该调用是 ASP.NET Web 窗体设计器所必需的。
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// 设计器支持所需的方法 - 不要使用代码编辑器修改
        /// 此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);
            this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click);
            this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click);
            this.btnReturn.Click += new System.EventHandler(this.btnReturn_Click);
            this.Load += new System.EventHandler(this.Page_Load);
        }

        #endregion
    }
}